<template>
    <div class="input-tag-container"
         disabled
         :class="containerClass"
         :style="{'--primaryColor':primaryColor,'--hoverColor':hoverColor}"
         v-click-out-side="outSide" @click="inputBlur">
        <div class=input-tag-body ref="tagBody">
            <tag :theme="theme" ref="inputTags" class="input-tag" v-for="(item,index) in selectTags"
                 :title="item[props.label]"
                 :key="index"
                 :disabled="disabled"
                 @close="tagClose(item,index)"></tag>
            <div class="input-tag-input" v-if="!disabled">
                <input class="input-tag-input-input" :class="{'input-tag-input-input-dark':theme==='dark'}"
                       ref="selectInput" v-model="inputString" @keydown.enter="searchInput"
                       :style="{width:inputWidth+'px'}" :placeholder="placeholder"
                       @keydown.delete="deleteInput">
                <div class="input-tag-draw" :class="{'input-tag-draw-dark':theme==='dark'}" v-if="visible">
                    <ul v-if="searchArray.length>0">
                        <li v-for="(item,index) of searchArray" :key="index" @click="itemClick(item)">
                            <tags-option :theme="theme" :item="item" :label="item[props.label]"
                                         :value="item[props.value]">
                                <slot :option="item"></slot>
                            </tags-option>
                        </li>
                    </ul>
                    <slot name="empty" v-else>
                        <div style="text-align: center;margin-top: 24px">
                            <empty/>
                            <div style="color: #bfbfbf">暂无数据</div>
                        </div>
                    </slot>
                </div>
            </div>
        </div>
        <div class="input-tag-clear" :class="{'input-tag-clear-visible':showFocused}" v-if="showClear" @click="clear">
            <icon-close-circle/>
        </div>
    </div>
</template>

<script>
    import tag from './tag'
    import TagsOption from './option'
    import ClickOutSide from '../directives/clickOutside'
    import {getDarkOrLightColor, validateArray, validateNull} from "../util/util";
    import empty from './icon-empty'
    import IconCloseCircle from "./icon-close-circle";

    export default {
        name: "inputTag",
        components: {
            IconCloseCircle,
            tag,
            TagsOption,
            empty
        },
        directives: {ClickOutSide},
        data() {
            return {
                tags: [],
                inputString: "",
                selectTags: [], // 选择的tag
                searchArray: [], // 搜索的结果
                visible: false, // 是否显示下拉框
                inputWidth: 150,
                focused: false
            };
        },
        provide() {
            return {
                'inputTag': this
            };
        },
        mounted() {
            this.inputWidth = this.$refs.tagBody.offsetWidth
            window.addEventListener('resize', () => {
                this.debounce(this.changeInputWidth(), 100)
            }, false)
            this.$once('hook:beforeDestroy', () => {
                window.removeEventListener('resize', () => {
                    this.debounce(this.changeInputWidth(), 100)
                }, false)
            })
        },
        props: {
            primaryColor: {
                type: String,
                default: '#177ddc'
            },
            isSearch: {
                type: Boolean,
                default: false
            },
            props: {
                type: Object,
                default: () => ({
                    label: 'label',
                    value: 'value'
                })
            },
            value: {
                type: Array,
                default: () => ([])
            },
            placeholder: {
                type: String,
                default: '请输入回车搜索'
            },
            theme: {
                type: String,
                default: 'default'
            },
            disabled: { // 是否禁用
                type: Boolean,
                default: false
            },
            clearable: { // 是否清空
                type: Boolean,
                default: false
            }
        },
        computed: {
            hoverColor: function () {
                return this.theme === 'dark' ? getDarkOrLightColor(this.primaryColor, 0.8) : getDarkOrLightColor(this.primaryColor, -0.8)
            },
            showFocused() {
                return !this.disabled && this.focused
            },
            showClear() {
                return (this.selectTags.length > 0 || this.inputString&&this.inputString.length > 0)&&this.clearable
            },
            containerClass() {
                const basicClass = 'input-tag-container'
                let clazz = []
                let className = basicClass
                if (this.theme === 'dark') {
                    className = className + '-dark'
                    clazz.push(className)
                }
                if (this.disabled) {
                    className = className + '-disabled'
                    clazz.push(className)
                }
                if (!this.disabled && this.focused) {
                    clazz.push(basicClass + '-hover')
                }
                return clazz
            }
        },
        watch: {
            value: {
                handler: function (val, oldVal) {
                    if (val !== oldVal) {
                        this.selectTags = val
                    }
                },
                deep: true,
                immediate: true
            },
            selectTags: {
                handler: function (val, oldVal) {
                    if (val) {
                        this.changeInputWidth()
                    }
                },
                deep: true,
                immediate: true
            },
            // disabled:{
            //     handler: function (val, oldVal) {
            //         console.log(val)
            //         if (val!==oldVal) {
            //             this.changeInputWidth()
            //         }
            //     },
            // }
        },
        methods: {
            itemClick(item) {
                this.selectTags.push(item)
                this.searchArray = []
                this.visible = false
                this.inputString = undefined
                this.$emit('input', this.selectTags)
            },
            outSide() {
                this.focused = false
                this.visible = false
                this.searchArray = []
                this.inputString = undefined
            },
            searchCallback(value) {
                if (!validateNull(value) && validateArray(value)) {
                    this.searchArray = value
                }
                this.visible = true
            },
            searchInput() {
                if (this.inputString) {
                    if (this.isSearch) {
                        this.$emit('search', this.inputString, this.searchCallback)
                    } else {
                        let tag = {}
                        tag[this.props.label] = this.inputString
                        tag[this.props.value] = this.inputString
                        this.selectTags.push(tag)
                        this.inputString = undefined
                    }
                    this.$emit('input', this.selectTags)
                }
            },
            tagClose(tag, index) {
                this.selectTags.splice(index, 1)
                this.$emit('input', this.selectTags)
                this.$emit('deleteTag', tag, index)
            },
            inputBlur() {
                if(!this.disabled){
                    this.focused = true
                    this.$refs.selectInput.focus()
                }
            },
            deleteInput() {
                if (this.inputString && this.inputString !== "") {

                } else if (this.selectTags.length > 0) {
                    this.selectTags.shift()
                    this.$emit('input', this.selectTags)
                }
                this.visible = false
            },
            changeInputWidth() {
                this.$nextTick(() => {
                    try {
                        let main = this.$refs.tagBody.offsetWidth
                        let total = 0;
                        if (this.$refs.inputTags && this.$refs.inputTags.length > 0) {
                            total = this.$refs.inputTags.reduce(function (prev, curr) {
                                let total = prev + curr.$el.offsetWidth + 6;
                                if (total > main) {
                                    return curr.$el.offsetWidth + 6
                                } else {
                                    return total
                                }
                            }, 0)
                        }
                        let inputWidth = main - total - 4
                        this.inputWidth = inputWidth > 30 ? inputWidth : main
                    } catch (e) {
                        this.inputWidth = 150
                    }
                })
            },
            debounce(fn, wait) {
                this.timeout = null;
                return function () {
                    if (this.timeout !== null) clearTimeout(this.timeout);
                    this.timeout = setTimeout(fn, wait);
                }
            },
            clear() {
                this.selectTags = []
                this.inputString = undefined
                this.visible = false
                this.searchArray=[]
                this.$emit('input', this.selectTags)
            }
        }
    };
</script>

<style scoped>
    .input-tag-container {
        position: relative;
        box-sizing: border-box;
        background-color: #fff;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        user-select: none;
        padding-top: 4px;
        box-sizing: border-box;
        min-height: 32px;
    }

    .input-tag-container-disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .input-tag-container-dark {
        background-color: #141414;
        border: 1px solid #d9d9d9;
    }

    .input-tag-container-dark-disabled {
        background: #2a2a2a;
        cursor: not-allowed;
    }

    .input-tag-container-hover {
        border: 1px solid var(--primaryColor);
        box-shadow: 0px 0px 5px var(--primaryColor);
    }

    .input-tag-body {
        margin: 0 16px 0 6px;
    }

    .input-tag-body-clear {
        margin: 0 18px 0 6px
    }

    .input-tag-input {
        margin-bottom: 4px;
        position: relative;
        display: inline-block;
    }

    .input-tag-input-input {
        height: 24px;
        font-size: 16px;
        padding: 0;
        min-width: 25px !important;
        border: none !important;
        outline: none !important;
        color: rgba(0, 0, 0, 0.65) !important
    }

    .input-tag-input-input-dark {
        color: white !important;
        background-color: #141414 !important;
    }

    .input-tag-input-input-dark::-webkit-input-placeholder {
        color: rgba(255, 255, 255, .65);
    }

    .input-tag-input-input-dark:-moz-placeholder {
        color: rgba(255, 255, 255, .65);
    }

    .input-tag-input-input-dark::-moz-placeholder {
        color: rgba(255, 255, 255, .65);
    }

    .input-tag-input-input-dark:-ms-input-placeholder {
        color: rgba(255, 255, 255, .65);
    }

    .input-tag {
        margin-right: 3px;
        margin-bottom: 4px;
    }

    .input-tag:last-child {
        margin-bottom: 3px;
    }

    .input-tag-draw {
        position: absolute;
        top: 35px;
        left: 0px;
        box-shadow: #577d9b 1px 1px 5px;
        min-width: 200px;
        min-height: 200px;
        max-height: 400px;
        overflow: auto;
        padding: 6px 0px;
        border-radius: 3px;
        background: white;
    }

    .input-tag-draw-dark {
        background: #141414;
    }

    .input-tag-draw::-webkit-scrollbar {
        width: 0;
    }

    /*.input-tag-draw::-webkit-scrollbar-track-piece {*/
    /*     background-color: transparent;*/
    /* }*/
    /*.input-tag-draw::-webkit-scrollbar {*/
    /*     width: 0px;*/
    /*     height: 7px;*/
    /*     background-color: transparent;*/
    /* }*/
    /*.input-tag-draw::-webkit-scrollbar-thumb {*/
    /*     border-radius: 5px;*/
    /*     background-color: hsla(220, 4%, 58%, .3);*/
    /* }*/

    .input-tag-draw li {
        list-style-type: none
    }

    .input-tag-draw ul {
        padding: 0px;
        margin: 0px;
    }

    .input-tag-clear {
        position: absolute;
        right: 6px;
        top: 50%;
        transform: translateY(-55%);
        cursor: pointer;
        visibility: hidden;
    }

    .input-tag-clear-visible {
        visibility: visible;
    }

    .input-tag-clear:before {
        width: 25px;
        height: 25px;
    }
</style>
